package net.lastcoder.ifserver.web;


import net.lastcoder.ifserver.game.Client;
import net.lastcoder.ifserver.game.GameManager;
import net.lastcoder.ifserver.game.Role;
import net.lastcoder.ifserver.game.Vector2;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * auth: WenYF
 * date: 2017/3/13
 */
@WebSocket(maxTextMessageSize = 64 * 1024)
public class ClientWebHandler {
    private static final Logger Log = LoggerFactory.getLogger(ClientWebHandler.class);

    private Map<Session, FastJsonParser> jsonParserMap = new HashMap<>();

    public ClientWebHandler() {
        Log.debug("ClientWebHandler construct");
    }

    @OnWebSocketClose
    public void onClose(Session session, int statusCode, String reason) {
        Log.debug("Closing web connection, statusCode = " + statusCode + " reason = " + reason);
        Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap();
        String userid = parameterMap.get("userid").get(0);
        GameManager.getInstance().removeClientAndRole(userid);
    }

    @OnWebSocketError
    public void onError(Session session, Throwable t) {
        Log.error("Closing web connection due to error in session: ", t);
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {
        Log.debug("onConnect session = " + session);

        // 设置超时断开连接时间
        session.setIdleTimeout(60000 * 10);
        
        Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap();
        jsonParserMap.put(session, new FastJsonParser());
        
        String userid = parameterMap.get("userid").get(0);

        Client client = new Client();
        client.setSession(session);
        client.setUserid(userid);

        GameManager.getInstance().addClient(client);
    }

    @OnWebSocketMessage
    public void onMessage(Session session, String message) {
        Log.debug("onMessage session = " + session);
        Log.debug("onMessage message = " + message);
        FastJsonParser fastJsonParser = jsonParserMap.get(session);
        fastJsonParser.read(message);

        Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap();
        String userid = parameterMap.get("userid").get(0);

        while (fastJsonParser.hasPacket()) {
            String msg = fastJsonParser.getPacket();
            GameManager.getInstance().recvMessage(userid, msg);
        }
    }
}
